from django.shortcuts import render
from django.views import View
from django import http
import logging, json, re
from django.contrib.auth import login, authenticate, logout
# from apps.users.models import User
from apps.users.models import User
# Create your views here.
from django.contrib.auth import login, authenticate, logout
logger = logging.getLogger('django')



class RegisterView(View):
    """用户注册    """

    def post(self, request):
        """实现注册逻辑"""
        # 接收参数：请求体中的JSON数据 request.body
        json_dict = json.loads(request.body.decode())

        # 提取参数
        mobile = json_dict.get('mobile')

        password = json_dict.get('password')
        # password2 = json_dict.get('password2')
        # username = json_dict.get('username')
        # 提取短信验证码
        phonecode = json_dict.get('phonecode')


        if not all([ password, mobile, phonecode]):

        # if not all([username, password, password2, mobile, sms_code_client, allow]):
            # 如果缺少了必传参数，就返回400的状态码和错误信息，立马终止逻辑
            return http.JsonResponse({'errno': 4001, 'errmsg': '缺少必传参数'})

        # 判断密码是否满足项目的格式要求
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            # 如果密码不满足格式要求，返回错误信息，立马终止逻辑
            return http.JsonResponse({'errno': 4001, 'errmsg': '参数password有误'})

        # 判断用户两次输入的密码是否一致
        # if password != password2:
        #     return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})
        # 判断手机号是否满足项目的格式要求

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4001, 'errmsg': '参数mobile有误'})

        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        # redis_conn = get_redis_connection('verify_code')
        # sms_code_server = redis_conn.get('sms_%s' % mobile) # sms_code_server是bytes
        # 判断短信验证码是否过期
        # if not sms_code_server:
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        # if sms_code_client != sms_code_server.decode():
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})


        try:
            user = User.objects.create_user(password=password,username=mobile,mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 4001, 'errmsg': '注册失败'})

        # 实现状态保持：因为美多商城的需求是注册成功即登录成功
        # 我们记住当前的用户登录过的，cookie机制(不选的)，session机制（OK）
        # 如何证明当前的用户登录过，选择session机制，包含了记住登录状态和校验登录的状态
        # login()方法是Django提供的用于实现登录、注册状态保持
        # login('请求对象', '注册后或者登录认证后的用户')
        # login(request, user)

        # 在注册成功后，将用户名写入到cookie，将来会在页面右上角展示
        # response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        # response.set_cookie('username', user.username, max_age=3600*24*14)

        # 响应结果：如果注册成功，前端会把用户引导到首页
        return http.JsonResponse({'errno': 0, 'errmsg': '注册成功'})


class LoginView(View):
    """用户登录
    GET /login/
    """

    def post(self, request):
        """实现用户登录逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        # 该参数既可以是用户名，也可以是手机号
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')

        # 校验参数
        if not all([mobile, password]):
            return http.JsonResponse({'errno': 4001, 'errmsg': '缺少必传参数'})
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', account):
        #     return http.JsonResponse({'code': 400, 'errmsg': '参数username格式错误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4001, 'errmsg': '参数mobile有误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'errno': 4001, 'errmsg': '参数password格式错误'})

        user = authenticate(request=request, username=mobile, password=password)
        # 判断用户认证是否成功
        if not user:
            return http.JsonResponse({'errno': 4001, 'errmsg': '用户名或密码错误'})

        # 实现状态保持
        login(request, user)

        request.session.set_expiry(14* 24 * 3600)

        # 在登录成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'errno': 0, 'errmsg': '登录成功'})
        response.set_cookie('name', user.username, max_age=3600*24*14)

        # 响应结果
        # return http.JsonResponse({'errno': 0, 'errmsg': '登录成功'})
        return response

    def get(self,request):
        user=request.user
        user_id=user.id

        if not user.is_authenticated:
            return http.JsonResponse({'errno': 4101, 'errmsg': '未登录'})

        return http.JsonResponse({
            "errno": "0",
            "errmsg": "已登录",
            "data": {
                "name": user.username,
                "user_id":user.id
            }
        })

    def delete(self,request):

        logout(request)

        # 清理用户名cookie
        response = http.JsonResponse({
            "errno": "0",
            "errmsg": "已登出"
        })
        response.delete_cookie('username')

        return response
